library MarksmanScope initializer init requires LegacySystem


	private function Trig_Marksman_Scope_Conditions takes nothing returns boolean
		return GetSpellAbilityId() == 'A02I'
	endfunction

	private function ScopeScan takes nothing returns boolean
		return GetUnitPointValue(GetFilterUnit())==50 and GetWidgetLife(GetFilterUnit())>0.405 and GetUnitTypeId(GetFilterUnit())!='e00C'
	endfunction

	private function OpticalScope takes nothing returns nothing
		local unit u = GetTriggerUnit()
		local unit u2
		local integer scopelevel = GetUnitAbilityLevel(u,'A02I')
		local real focus = 60.0-(5*I2R(scopelevel))
		local location l
		local group g
		local real dx
		local real dy
		local real x
		local real y
		local integer scan = 0
		local location target = GetSpellTargetLoc()
		local location origin = GetUnitLoc(u)

		set x =  DistanceBetweenPoints(target,origin)
		if(x < 0) then 
			set x = x * -1.0
		endif

		call RemoveLocation(target)
		call RemoveLocation(origin)
		set origin = null
		set target = null
		
		if(x>=3000) then
			 set u = null
			 set u2 = null
			 set g = null
			 set l = null
			 return
		endif
	  

		if GetSpellAbilityId()=='A02I' then
			if scopelevel>3 then
				call UnitAddAbility(u,'A089') //+80 dmg
			else
				call UnitAddAbility(u,'A07R') //+40 dmg
			endif
			call UnitAddAbility(u,'A07K') //LOS reduction
			call UnitAddAbility(u,'A088') //AS reduction
			if scopelevel>=3 then
				call UnitAddAbility(u,'A079') //Camoflouge (Optical Scope)
				set l = GetSpellTargetLoc()
				set x = GetLocationX(l)
				set y = GetLocationY(l)
				set g = AMGetUnitsInRange(1200, l, Condition(function ScopeScan))
				loop
					set u2 = FirstOfGroup(g)
					exitwhen u2==null
					set dx = GetUnitX(u2) - x
					set dy = GetUnitY(u2) - y
					if scan<6 then
						call PingMinimapEx(GetUnitX(u2),GetUnitY(u2),3.0,242,51,51,false)
						set scan = scan + 1
					endif
					call GroupRemoveUnit(g,u2)
				endloop
				call RemoveLocation(l)
				call DestroyGroup(g)
			endif
			call ShiftMoveSpeed(u,-focus)
			call PolledWait(5.5)
			if GetWidgetLife(u)>0.405 then
				call UnitRemoveAbility(u,'A07K')
				call UnitRemoveAbility(u,'A07R')
				call UnitRemoveAbility(u,'A079')
				call UnitRemoveAbility(u,'A088')
				call UnitRemoveAbility(u,'A089')
				call ShiftMoveSpeed(u,focus)
			endif
		endif 
		
		set u = null
		set u2 = null
		set g = null
		set l = null
	endfunction


	private function init takes nothing returns nothing
		local trigger t
		set t = CreateTrigger(  ) 
		call TriggerRegisterAnyUnitEventBJ( t, EVENT_PLAYER_UNIT_SPELL_EFFECT )	
		call TriggerAddCondition( t, Condition( function Trig_Marksman_Scope_Conditions ) )
		call TriggerAddAction( t, function OpticalScope )
	endfunction




endlibrary